//
//  THJEditComapnInfoVC.m
//  THJXHW
//
//  Created by 河南德艺 on 2017/12/9.
//  Copyright © 2017年 河南德艺. All rights reserved.
//

#import "THJEditComapnInfoVC.h"
#import "TextFieldCell.h"
#import "CreateTableModel.h"
#import "THJCompanyAddressCell.h"
#import "THJAddressSelectVC.h"
#import "ZBNetworking.h"
#import "THJSelectView.h"
@interface THJEditComapnInfoVC ()<UITableViewDelegate,UITableViewDataSource,THJAddressSelectVCDelegate,THJSelectViewDelegate>
{
    UILabel * addressLab;
    UITextField * detialTf;
    NSString * addressId;
    NSInteger selectIndex;
}
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) NSMutableDictionary *formDict;
@property (nonatomic,strong) NSMutableArray *selectArr;
@property (nonatomic,strong) UILabel *companyLab;
@property (nonatomic,strong) UILabel *companyLab2;
@property(nonatomic,strong)THJSelectView * selectView;
@end

@implementation THJEditComapnInfoVC
-(THJSelectView*)selectView{
//    if(!_selectView){
        _selectView = [[THJSelectView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _selectView.delegate = self;
        _selectView.listKey = @"1";
//    }
    return _selectView;
}
-(UILabel*)companyLab{
    if(!_companyLab){
        _companyLab = [[UILabel alloc] init];
        _companyLab.text = @"公司名称";
        [_companyLab setFont:[UIFont systemFontOfSize:17]];
        _companyLab.frame = CGRectMake(10, 5, 70, 40);
        [_companyLab setFont:[UIFont systemFontOfSize:15]];
    }
    return _companyLab;
}
-(UILabel*)companyLab2{
    if(!_companyLab2){
        _companyLab2 = [[UILabel alloc] init];
        [_companyLab2 setFont:[UIFont systemFontOfSize:16]];
        _companyLab2.textColor = SingleColor(darkGrayColor);
        _companyLab2.frame = CGRectMake(90, 5, ScreenWidth - 90, 40);
    }
    return _companyLab2;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if(KIsiPhoneX){
        [self setXNavBarWithTitle:@"编辑企业信息"];
    }else{
        [self setNavBarWithTitle:@"编辑企业信息"];
    }
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NavbarHeight, ScreenWidth, ScreenHeight - NavbarHeight - 60) style:UITableViewStylePlain];
    [self.tableView registerNib:[UINib nibWithNibName:@"THJCompanyAddressCell" bundle:nil] forCellReuseIdentifier:@"address"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
   
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorInset = UIEdgeInsetsZero;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self action:@selector(commitAction)];
    self.navigationItem.rightBarButtonItem = item;
    
    self.formDict = [NSMutableDictionary dictionary];
    [self creatData];
    [self getData];
    // Do any additional setup after loading the view from its nib.
}
- (void)commitAction{
    NSLog(@"%@",self.formDict);
}
- (void)creatData
{
    self.dataArray = @[].mutableCopy;
    NSArray * titleArr = @[@"公司类型",@"经营模式",@"公司规模",@"注册年份",@"注册资本",@"经营范围",@"主要销售",@"经主要采购",@"公司电话",@"公司传真",@"公司网址"];
    NSArray * placeholderArr = @[@"选择公司类型",@"选择公司模式",@"选择公司规模",@"输入公司注册年份",@"输入公司注册资本",@"输入公司经营范围",@"输入公司主要销售",@"输入公司经主要采购",@"输入公司电话（选填）",@"输入公司传真（选填）",@"输入公司网址（选填）"];
     NSArray * keyArr = @[@"type",@"mode",@"size",@"regyear",@"capital",@"business",@"sell",@"buy",@"telephone",@"fax",@"homepage"];
    for (NSInteger i = 0; i<11; i++) {
        CreateTableModel *name = [CreateTableModel new];
        name.cellType = CreateTableTFCell;
        name.title = titleArr[i];
        name.placeholder = placeholderArr[i];
        //提交到服务器的key
        name.key = keyArr[i];
        [self.dataArray addObject:name];
    }
}
#pragma mark - UITableDelegate & UITableViewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count+2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    if (indexPath.row == 1) {
        THJCompanyAddressCell * cell = [tableView dequeueReusableCellWithIdentifier:@"address" forIndexPath:indexPath];
        addressLab = cell.addressLab;
        detialTf = cell.detailAddressTf;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.selectBtn addTarget:self action:@selector(addressSelect) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else if(indexPath.row == 0){
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if(!cell){
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:@"cell"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.contentView addSubview:self.companyLab];
        [cell.contentView addSubview:self.companyLab2];
        return cell;
    }
    else{
         CreateTableModel *model = self.dataArray[indexPath.row - 2];
        static NSString *cellID = @"textFieldCellID";
        TextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[TextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            //监听textField输入
            [cell textFieldAddObserver:self selector:@selector(textFieldValueChange:)];
        }
        cell.formDict = self.formDict;
        cell.creatTableModel = model;
        if(indexPath.row>1 && indexPath.row<5){
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
            [btn setImage:kGetImage(@"xjt") forState:UIControlStateNormal];
            btn.frame = CGRectMake(ScreenWidth - 50, 10, 30, 30);
            btn.tag = indexPath.row;
            [btn addTarget:self action:@selector(selectView:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:btn];
        }
        return cell;
        
    }
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 1){
        return 95;
    }else{
        return 50;
    }
}
-(void)selectView:(UIButton*)btn{
     selectIndex = btn.tag;
     UIWindow * window = [UIApplication sharedApplication].keyWindow;
     [self setStateBarColor:SingleColor(clearColor)];
    if(selectIndex == 2){
        NSLog(@"2");
        self.selectView.dataArr = self.selectArr = [NSMutableArray arrayWithObjects:@{@"1":@"国有企业"},@{@"1":@"集体所有制"},@{@"1":@"私营企业"},@{@"1":@"股份制企业"},@{@"1":@"联营企业"},@{@"1":@"外商投资企业"},@{@"1":@"股份合作制企业"},@{@"1":@"港澳台资企业"},nil];
    }else if(selectIndex == 3){
        NSLog(@"3");
        self.selectView.dataArr = self.selectArr = [NSMutableArray arrayWithObjects:@{@"1":@"制造商"},@{@"1":@"贸易商"},@{@"1":@"服务商"},nil];
    }else if(selectIndex == 4){
        NSLog(@"4");
         self.selectView.dataArr = self.selectArr = [NSMutableArray arrayWithObjects:@{@"1":@"1-49人"},@{@"1":@"50-99人"},@{@"1":@"100-499人"},@{@"1":@"500-999人"},@{@"1":@"1000-3000人"},@{@"1":@"3000-5000人"},@{@"1":@"5000-10000人"},@{@"1":@"10000人以上"},nil];
    }
     [window addSubview:_selectView];
}
-(void)addressSelect{
    THJAddressSelectVC * vc = [[THJAddressSelectVC alloc] init];
    vc.delegate = self;
    vc.urlStr = [NSString stringWithFormat:@"%@%@",THJUrlDomain,@"index.php?f=Area&r=Area"];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)selectIndex:(NSInteger)index{
    if(index != 999999){
        NSLog(@"index-%@",self.selectArr[index][@"1"]);
        NSString * obj = self.selectArr[index][@"1"];
        if(selectIndex == 2){
            [self.formDict setObject:obj forKey:@"type"];
            [_tableView reloadData];
        }else if (selectIndex == 3){
            [self.formDict setObject:obj forKey:@"mode"];
            [_tableView reloadData];
        }else if (selectIndex == 4){
            [self.formDict setObject:obj forKey:@"size"];
            [_tableView reloadData];
        }
    }
    
}
-(void)selectedAddress:(NSMutableString*)address AreaId:(NSString*)areaId{
    NSLog(@"%@",address);
    addressLab.text = address;
    addressId = areaId;
    [self.formDict setObject:addressId forKey:@"areaid"];
    [self.formDict setObject:address forKey:@"address"];
}
- (void)textFieldValueChange:(NSNotification *)note
{
    UITextField *textField = note.object;
    //可以这样取值
    NSString *name = self.formDict[@"name"];
    NSString *nickName = self.formDict[@"nickName"];
    NSString *psw = self.formDict[@"psw"];
    NSString *psw2 = self.formDict[@"psw2"];
    
    NSLog(@"现在输入的是：%@\nname = %@,\nnickName = %@,\npsw = %@,\npsw2 = %@,\n",textField.text,
          name,
          nickName,
          psw,
          psw2);
}
- (IBAction)suerBtnAction:(id)sender{
    NSLog(@"%@",self.formDict);
    if([addressLab.text isEqual:@"省市选择"]){
        [self HUDShowMsg:@"请选择省市" AfterDelayDimiss:1];
        return;
    }else if(!detialTf.text.length){
        [self HUDShowMsg:@"请填写详细地址" AfterDelayDimiss:1];
         return;
    }else if(!self.formDict[@"type"]){
        [self HUDShowMsg:@"请选择公司类型" AfterDelayDimiss:1];
         return;
    }else if(!self.formDict[@"mode"]){
        [self HUDShowMsg:@"请选择公司经营模式" AfterDelayDimiss:1];
         return;
    }else if(!self.formDict[@"size"]){
        [self HUDShowMsg:@"请选择公司经营规模" AfterDelayDimiss:1];
         return;
    }else if(!self.formDict[@"regyear"]){
        [self HUDShowMsg:@"请填写公司注册年份" AfterDelayDimiss:1];
         return;
    }else if(!self.formDict[@"capital"]){
        [self HUDShowMsg:@"请填写公司注册资本" AfterDelayDimiss:1];
         return;
    }else if(!self.formDict[@"business"]){
        [self HUDShowMsg:@"请填写公司经营范围" AfterDelayDimiss:1];
         return;
    }else if(!self.formDict[@"sell"]){
        [self HUDShowMsg:@"请填写公司销售产品" AfterDelayDimiss:1];
         return;
    }else if(!self.formDict[@"buy"]){
        [self HUDShowMsg:@"请填写公司采购产品" AfterDelayDimiss:1];
         return;
    }
    NSLog(@"%@",self.formDict);
    NSString * url = [NSString stringWithFormat:@"%@%@",THJUrlDomain,@"index.php?f=My_company&r=My_company&m=save"];
    [THJNetWork postDataFromUrl:url parameters:self.formDict Token:[THJTools getToken] callback:^(NSDictionary* receiveData, NSError *error) {
        NSLog(@"修改公司信息%@",receiveData);
        if([receiveData[@"status"] isEqual:@"200"]){
            [self HUDShowMsg:@"修改成功" AfterDelayDimiss:1];
            [self performSelector:@selector(pop) withObject:nil afterDelay:1];
        }
    }];
}
-(void)getData{
    __weak typeof(self) weekself = self;
    NSString * urlstr = [NSString stringWithFormat:@"%@index.php?f=My_company&r=My_company&m=get_info",THJUrlDomain];
    NSLog(@"公司信息url-%@",urlstr);
    [MBProgressHUD showMessage:@"" toView:self.view];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
        request.urlString=urlstr;
        request.apiType=ZBRequestTypeCache;
        [request setValue:[THJTools getToken] forHeaderField:@"token"];
    }  success:^(id responseObject,apiType type){
        NSDictionary * receiveData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [MBProgressHUD hideHUDForView:weekself.view animated:YES];
        NSLog(@"公司信息-%@",receiveData);
        if([receiveData[@"status"] isEqual:@"200"]){
            NSLog(@"公司信息-%@",receiveData);
            self.formDict = receiveData[@"data"];
            [_tableView reloadData];
            detialTf.text = receiveData[@"data"][@"address"];
            self.companyLab2.text = receiveData[@"data"][@"company"];
        }
    } failed:^(NSError *error){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"error-%@",error);
    }];
}
//因为监听了textField通知，所以记得要在注销时，注销通知
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
